<template>
  <div class="payment-method">
    <div class="amount-section">
      <div class="amount-card">
        <div class="amount-label">待支付金额</div>
        <div class="amount-value">¥ {{ paymentData.amount.toFixed(2) }}</div>
      </div>
    </div>

    <div class="card">
      <div class="card-header">
        <el-icon class="card-header-icon"><CreditCard /></el-icon>
        <span>选择支付方式</span>
      </div>

      <div class="payment-options">
        <div 
          class="payment-option"
          :class="{ active: selectedMethod === 'alipay' }"
          @click="selectPaymentMethod('alipay')"
        >
          <div class="option-left">
            <div class="option-icon alipay">
              <el-icon><ShoppingBag /></el-icon>
            </div>
            <div class="option-info">
              <div class="option-title">支付宝支付</div>
              <div class="option-desc">推荐使用支付宝扫码支付</div>
            </div>
          </div>
          <div class="option-right">
            <el-radio :value="selectedMethod === 'alipay'" />
          </div>
        </div>

        <div 
          class="payment-option"
          :class="{ active: selectedMethod === 'wechat' }"
          @click="selectPaymentMethod('wechat')"
        >
          <div class="option-left">
            <div class="option-icon wechat">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="option-info">
              <div class="option-title">微信支付</div>
              <div class="option-desc">推荐使用微信扫码支付</div>
            </div>
          </div>
          <div class="option-right">
            <el-radio :value="selectedMethod === 'wechat'" />
          </div>
        </div>

        <div 
          class="payment-option"
          :class="{ active: selectedMethod === 'unionpay' }"
          @click="selectPaymentMethod('unionpay')"
        >
          <div class="option-left">
            <div class="option-icon unionpay">
              <el-icon><CreditCard /></el-icon>
            </div>
            <div class="option-info">
              <div class="option-title">银联支付</div>
              <div class="option-desc">支持储蓄卡、信用卡</div>
            </div>
          </div>
          <div class="option-right">
            <el-radio :value="selectedMethod === 'unionpay'" />
          </div>
        </div>

        <div 
          class="payment-option"
          :class="{ active: selectedMethod === 'digitalrmb' }"
          @click="selectPaymentMethod('digitalrmb')"
        >
          <div class="option-left">
            <div class="option-icon digitalrmb">
              <el-icon><Coin /></el-icon>
            </div>
            <div class="option-info">
              <div class="option-title">数字人民币支付</div>
              <div class="option-desc">使用数字人民币钱包支付</div>
            </div>
          </div>
          <div class="option-right">
            <el-radio :value="selectedMethod === 'digitalrmb'" />
          </div>
        </div>
      </div>
    </div>

    <div class="security-tips">
      <el-icon class="security-icon"><Lock /></el-icon>
      <span>支付安全保证，您的信息不会泄露</span>
    </div>

    <div class="action-buttons">
      <button class="back-button" @click="$emit('prev-step')">返回上一步</button>
      <button
        class="confirm-button"
        @click="handleConfirmPay"
        :class="{ loading: payLoading }"
        :disabled="!selectedMethod"
      >
        {{ payLoading ? "支付中..." : "确认支付" }}
      </button>
    </div>

    <!-- 支付二维码弹窗 -->
    <el-dialog
      v-model="showQRCode"
      :title="qrCodeTitle"
      width="400px"
      align-center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="qr-code-container">
        <div class="qr-code-placeholder">
          <el-icon class="qr-icon"><Picture /></el-icon>
          <div class="qr-text">支付二维码</div>
          <div class="payment-amount">¥ {{ paymentData.amount.toFixed(2) }}</div>
        </div>
        
        <div class="countdown-section">
          <div class="countdown-text">
            请在 <span class="countdown-number">{{ countdown }}</span> 秒内完成支付
          </div>
          <div class="countdown-progress">
            <div 
              class="countdown-bar" 
              :style="{ width: countdownProgress + '%' }"
            ></div>
          </div>
        </div>
        
        <div class="payment-tips">
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>请使用{{ getPaymentMethodText(selectedMethod) }}扫描二维码</span>
          </div>
          <div class="tip-item">
            <el-icon><InfoFilled /></el-icon>
            <span>支付成功后会自动跳转</span>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <button class="cancel-button" @click="cancelPayment">
            取消支付
          </button>
          <button class="success-button" @click="simulateSuccess">
            模拟支付成功
          </button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, computed } from 'vue'
import { ElRadio, ElIcon, ElDialog,ElMessage } from 'element-plus'
// 引入后端支付接口
import { completePayment } from '@/api/selfPaymentService';

const props = defineProps({
  paymentData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['next-step', 'prev-step', 'payment-success', 'payment-failed'])

const selectedMethod = ref('wechat')
const payLoading = ref(false)
const showQRCode = ref(false)
const countdown = ref(5)
const countdownTimer = ref(null)

// 计算倒计时进度
const countdownProgress = computed(() => {
  return (countdown.value / 5) * 100
})

// 二维码弹窗标题
const qrCodeTitle = computed(() => {
  return `${getPaymentMethodText(selectedMethod.value)} - 扫码支付`
})

// 选择支付方式
const selectPaymentMethod = (method) => {
  selectedMethod.value = method
}

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methods = {
    'wechat': '微信支付',
    'alipay': '支付宝支付',
    'unionpay': '银联支付',
    'digitalrmb': '数字人民币支付'
  }
  return methods[method] || '未知支付方式'
}

// 确认支付
const handleConfirmPay = () => {
  if (!selectedMethod.value) return

  payLoading.value = true
  
  // 模拟支付处理
  setTimeout(() => {
    payLoading.value = false
    showQRCode.value = true
    startCountdown()
  }, 1000)
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 30
  countdownTimer.value = setInterval(() => {
    countdown.value--
    
    if (countdown.value <= 0) {
      // 倒计时结束，调用真实支付接口
      handleRealPayment();
    }
  }, 1000)
}

// ==== 完成支付 调用真实支付接口 ==== 
const handleRealPayment = async () => {
  clearInterval(countdownTimer.value)
  try {
    // 准备支付数据
    const paymentRequest = {
      paymentId: props.paymentData.paymentId,
      examinationOrderId: props.paymentData.examinationOrderId,
      amount: props.paymentData.amount,
      visitNumber: props.paymentData.visitNumber,
      patientName: props.paymentData.patientName,
      paymentMethod: selectedMethod.value,
      // 其他必要的支付参数
      visitId: props.paymentData.visit_id || JSON.parse(localStorage.getItem("currentPatientVisit")).visit_id
    }
    
    console.log('发起支付请求:', paymentRequest);
    
    // 调用后端支付接口
    const response = await completePayment(paymentRequest);
    
    if (response && response.code === 200) {
      // 支付成功 返回结果
      const paymentResult = {
        paymentMethod: selectedMethod.value,
        transactionId: response.data.paymentNo,  // 支付订单主单号
        orderId: props.paymentData.orderId, // 项目订单id
        examinationOrderId: props.paymentData.examinationOrderId, // 同上：项目订单id
        amount: props.paymentData.amount,  //支付总费用
        visitNumber: props.paymentData.visitNumber,
        patientName: props.paymentData.patientName,
        // 后端返回的其他数据
        ...response.data
      }
      
      showQRCode.value = false;
      ElMessage.success('支付成功！');
      emit('payment-success', paymentResult);
    } else {
      // 支付失败
      throw new Error(response?.message || '支付失败');
    }

    // emit('payment-success', paymentResult);
    
  } catch (error) {
    console.error('支付失败:', error);
    showQRCode.value = false;
    ElMessage.error(error.message || '支付失败，请重试');
    
    const paymentResult = {
      paymentMethod: selectedMethod.value,
      paymentTime: new Date().toLocaleString('zh-CN'),
      transactionId: generateTransactionId(),
      errorMessage: error.message || '支付失败，请重试',
      orderId: props.paymentData.orderId,
      paymentId: props.paymentData.paymentId,
      examinationOrderId: props.paymentData.examinationOrderId
    }
    
    emit('payment-failed', paymentResult);
  }
}

// 取消支付
const cancelPayment = () => {
  clearInterval(countdownTimer.value)
  showQRCode.value = false
  
  const paymentResult = {
    paymentMethod: selectedMethod.value,
    paymentTime: new Date().toLocaleString('zh-CN'),
    transactionId: generateTransactionId(),
    errorMessage: '用户取消支付',
    // 新增传递的订单和支付信息（即使取消也传递）
    orderId: props.paymentData.orderId,
    paymentId: props.paymentData.paymentId,
    examinationOrderId: props.paymentData.examinationOrderId
  }
  
  emit('payment-failed', paymentResult)
}

// 模拟支付成功（测试用）
const simulateSuccess = async () => {
  clearInterval(countdownTimer.value)
  
  await handleRealPayment();
}

// 生成交易单号
const generateTransactionId = () => {
  const timestamp = new Date().getTime()
  const random = Math.floor(Math.random() * 10000)
  return `T${timestamp}${random.toString().padStart(4, '0')}`
}
</script>

<style lang="scss" scoped>
.payment-method {
  width: 100%;
}

.amount-section {
  margin-bottom: 24px;
}

.amount-card {
  background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
  color: white;
  border-radius: 16px;
  padding: 30px;
  text-align: center;
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

.amount-label {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.amount-value {
  font-size: 42px;
  font-weight: 700;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f9fafb;
  border-bottom: 1px solid #eaeef2;
  font-weight: 500;
  color: #1f2f3d;
}

.card-header-icon {
  margin-right: 8px;
  color: #3b82f6;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px;
}

.payment-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #3b82f6;
    background: #f0f9ff;
  }
  
  &.active {
    border-color: #3b82f6;
    background: #f0f9ff;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
  }
}

.option-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.option-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
  
  &.wechat {
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
  }
  
  &.alipay {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  }
  
  &.unionpay {
    background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  }
  
  &.digitalrmb {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  }
}

.option-info {
  .option-title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
  }
  
  .option-desc {
    font-size: 14px;
    color: #64748b;
  }
}

.security-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 8px;
  color: #0369a1;
  margin: 24px 0;
}

.security-icon {
  margin-right: 8px;
  color: #0ea5e9;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 24px;
}

.back-button {
  flex: 1;
  height: 48px;
  background: white;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
  }
}

.confirm-button {
  flex: 1;
  height: 48px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover:not(:disabled) {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  }
  
  &:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
  }
  
  &.loading {
    opacity: 0.7;
    pointer-events: none;
  }
}

/* 二维码弹窗样式 */
.qr-code-container {
  text-align: center;
  padding: 10px 0;
}

.qr-code-placeholder {
  background: #f8fafc;
  border: 2px dashed #e2e8f0;
  border-radius: 12px;
  padding: 40px 20px;
  margin-bottom: 20px;
  
  .qr-icon {
    font-size: 64px;
    color: #cbd5e1;
    margin-bottom: 12px;
  }
  
  .qr-text {
    font-size: 16px;
    color: #64748b;
    margin-bottom: 8px;
  }
  
  .payment-amount {
    font-size: 24px;
    font-weight: 700;
    color: #ef4444;
  }
}

.countdown-section {
  margin-bottom: 20px;
  
  .countdown-text {
    font-size: 14px;
    color: #64748b;
    margin-bottom: 8px;
    
    .countdown-number {
      color: #ef4444;
      font-weight: 600;
      font-size: 16px;
    }
  }
  
  .countdown-progress {
    height: 6px;
    background: #e2e8f0;
    border-radius: 3px;
    overflow: hidden;
    
    .countdown-bar {
      height: 100%;
      background: linear-gradient(90deg, #10b981, #3b82f6);
      transition: width 1s linear;
      border-radius: 3px;
    }
  }
}

.payment-tips {
  background: #f0f9ff;
  border-radius: 8px;
  padding: 16px;
  text-align: left;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #0369a1;
  margin-bottom: 8px;
  font-size: 14px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .el-icon {
    color: #0ea5e9;
    font-size: 14px;
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.cancel-button {
  padding: 10px 20px;
  background: white;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
  }
}

.success-button {
  padding: 10px 20px;
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: linear-gradient(135deg, #059669 0%, #047857 100%);
  }
}

@media (max-width: 768px) {
  .payment-option {
    padding: 16px;
  }

  .option-left {
    gap: 12px;
  }

  .option-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }

  .action-buttons {
    flex-direction: column;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>